<?php
namespace WebIM\Store;

class Redis {
	/**
	 * @var \redis
	 */
	protected $redis;

	protected $history_fp;
	protected $history = array();
	protected $history_max_size = 100;
	protected $history_write_count = 0;
	//历史消息key
	protected $redis_history_key = 'webim_history';

	protected $last_day;

	static $prefix = "webim_";

	function __construct($host = '127.0.0.1', $port = 6379, $timeout = 0.0) {
		$redis = new \Redis();
		$redis->connect($host, $port, $timeout);
		$redis->auth('*%FAU^J09mNU*xNU');
		$this->redis = $redis;
	}

	function login($client_id, $info) {
		$info['ip'] = $this->getClientIp();
		$this->redis->set(self::$prefix . 'client_' . $client_id, json_encode($info));
		$this->redis->sAdd(self::$prefix . 'online', $client_id);
		$this->redis->hset('online_uid_client', $client_id,$info['uid']);
		$this->redis->hset('online_client_uid', $info['uid'], $client_id);

	}

	/**
	 * 下线
	 * @param  [type] $client_id [description]
	 * @return [type]            [description]
	 */
	function logout($client_id) {
		$this->redis->del(self::$prefix . 'client_' . $client_id); //修改bug
		$this->redis->sRemove(self::$prefix . 'online', $client_id);
		$uid = $this->redis->hget('online_uid_client',$client_id);
		$this->redis->hDel('online_uid_client', $client_id);
		$this->redis->hDel('online_client_uid', $uid);

	}
	/**
	 * 根据房间号登陆
	 * @param type $client_id
	 * @param array $info
	 */
	function loginByRoom($client_id, $info) {
		$info['ip'] = $this->getClientIp();
		$this->redis->hSet($info["room"],self::$prefix . 'client_' . $client_id, json_encode($info));
		$this->redis->sAdd($info["room"]."_".self::$prefix . 'online', $client_id);
		$this->redis->hSet("online",$client_id,$info["room"]);
		$this->redis->hSet("online_uid_client",$client_id,$info["uid"]);
		
	}

	/**
	 * 根据房间退出
	 * @param type $client_id
	 */
	function logoutByRoom($client_id) {
		$room=$this->redis->hGet("online",$client_id);
		$this->deleteUserByRoom($client_id,$room);
		$this->redis->hDel("online",$client_id);
		$this->redis->hDel("online_uid_client",$client_id);
	}
	function getOnlineUsers() {
		return $this->redis->sMembers(self::$prefix . 'online');
	}

	function getFormatUsers($users){
		foreach ($users as $key => $u) {
			$uid = $this->getClientUid($u);
			$all_user[$uid] = $u;
		}
		return array_values($all_user);
	}

	/**
	 * 根据房间获取在线用户
	 * @param type $room_id
	 * @return type
	 */
	function getOnlineUsersByRoom($room_id) {
		return $this->redis->sMembers($room_id."_".self::$prefix . 'online');
	}
	function getUsers($users) {
		$keys = array();
		$ret = array();

		foreach ($users as $v) {
			$keys[] = self::$prefix . 'client_' . $v;
		}

		$info = $this->redis->mget($keys);
		foreach ($info as $v) {
			$ret[] = json_decode($v);
		}
		return $ret;
	}
	
	/**
	 * 获取房间所有人信息
	 * @param type $users
	 * @param type $room_id
	 * @return type
	 */
	function getUsersByRoom($users,$room_id) {
		$ret = array();
		foreach ($users as $v) {
			$key=self::$prefix . 'client_' . $v;
			$ret[] = json_decode($this->redis->hGet($room_id,$key));
		}
		return $ret;
	}
	/**
	 * 删除房间内某用户
	 * @param type $fd
	 * @param type $room_id
	 * @return type
	 */
	function deleteUserByRoom($fd,$room_id) {
		$key=self::$prefix . 'client_' . $fd;
		$this->redis->hDel($room_id,$key);
		$this->redis->sRemove($room_id."_".self::$prefix . 'online', $fd);
	}
	/**
	 * 获取用户信息
	 * @param  [type] $userid [description]
	 * @return [type]         [description]
	 */
	function getUser($userid) {
		$ret = $this->redis->get(self::$prefix . 'client_' . $userid);
		$info = json_decode($ret, true);
		return $info;
	}

	/**
	 * 获取client_id对应用户uid
	 * 
	 * @param  [type] $userid [description]
	 * @return [type]         [description]
	 */
	function getClientUid($client_id) {
		$ret = $this->redis->hGet('online_uid_client' ,$client_id);
		return $ret;
	}

	/**
	 * 获取uid对应用户client_id
	 *
	 * @param  [type] $userid [description]
	 * @return [type]         [description]
	 */
	function getUidClient($uid) {
		$ret = $this->redis->hGet('online_client_uid' ,$uid);
		return $ret;
	}
	/**
	 * 根据房间获取用户信息
	 * @param type $userid
	 * @param type $room_id
	 * @return type
	 */
	function getUserByRoom($userid,$room_id) {
		$ret = $this->redis->hGet($room_id,self::$prefix . 'client_' . $userid);
		$info = json_decode($ret, true);
		return $info;
	}
	/**
	 * 添加历史消息
	 * @param [type] $userid [description]
	 * @param [type] $msg    [description]
	 */
	function addHistory($userid, $msg) {
		$info = $this->getUser($userid);

		$log['user'] = $info;
		$log['userid'] = $userid;
		$log['msg'] = $msg;
		$log['time'] = time();
		$log['type'] = empty($msg['type']) ? '' : $msg['type'];

		$this->history = json_decode($this->redis->get($this->redis_history_key), true);
		$this->history[] = $log;
		if (count($this->history) > $this->history_max_size) {
			//丢弃历史消息
			array_shift($this->history);
		}
		$this->redis->set($this->redis_history_key, json_encode($this->history));
	}
	/**
	 * 添加历史记录
	 * @param type $userid
	 * @param type $msg
	 */
	function addHistoryByRoom($userid, $msg) {
		$info = $this->getUserByRoom($userid,$msg["room"]);

		$log['user'] = $info;
		$log['userid'] = $userid;
		$log['msg'] = $msg;
		$log['time'] = time();
		$log['type'] = empty($msg['type']) ? '' : $msg['type'];
		$this->history = json_decode($this->redis->get($this->redis_history_key."_".$msg["room"]), true);
		$this->history[] = $log;
		if (count($this->history) > $this->history_max_size) {
			//丢弃历史消息
			array_shift($this->history);
		}
		$this->redis->set($this->redis_history_key."_".$msg["room"], json_encode($this->history));
	}
	/**
	 * 获得历史
	 * @param  integer $offset [description]
	 * @param  integer $num    [description]
	 * @return [type]          [description]
	 */
	function getHistory($offset = 0, $num = 100) {
		$this->history = json_decode($this->redis->get($this->redis_history_key), true);
		return $this->history;
	}
	/**
	 * 更具房间获取历史信息
	 * @param type $offset
	 * @param type $num
	 * @return type
	 */
	function getHistoryByRoom($room_id,$offset = 0, $num = 100) {
		$this->history = json_decode($this->redis->get($this->redis_history_key."_".$room_id), true);
		return $this->history;
	}
	/**
	 * 活期键值
	 * @param  [type] $key [description]
	 * @return [type]      [description]
	 */
	function get($key) {
		return json_decode($this->redis->get(self::$prefix . $key));
	}

    /**
     * @param $key
     * @param $value
     * @param int $timeout
     * @return bool
     */
    function set($key ,$value , $timeout = 86400){
        return $this->redis->set(self::$prefix . $key,json_encode($value) ,$timeout);
    }
	/**
	 *   * 获取客户端IP地址
	 *   * @return String
	 */
	function getClientIp() {
		$onlineip = '';
		if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
			$onlineip = getenv('HTTP_CLIENT_IP');
		} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
			$onlineip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
			$onlineip = getenv('REMOTE_ADDR');
		} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
			$onlineip = $_SERVER['REMOTE_ADDR'];
		}
		preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
		$onlineip = empty($onlineipmatches[0]) ? '0.0.0.0' : $onlineipmatches[0];
		return $onlineip;
	}
}